package com.ds.lens.data.intercept;

import com.ds.lens.data.common.error.ErrorCodeException;
import com.ds.lens.data.vo.BaseOutVO;
import com.ds.lens.data.vo.enums.DataCommonVOMessageEnum;
import com.ds.lens.data.vo.factory.VOFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author WeiShaoying
 */
@Slf4j
@ControllerAdvice
public class ControllerIntercept {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public BaseOutVO throwsMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return VOFactory.getBaseOutVO(DataCommonVOMessageEnum.COMMON_PARAMETER_IS_NULL.getCode(),
                e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    @ResponseBody
    public BaseOutVO throwsMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        return VOFactory.getBaseOutVO(DataCommonVOMessageEnum.COMMON_PARAMETER_IS_NULL.getCode(),
                e.getMessage());
    }

    @ExceptionHandler(value = {HttpMessageNotReadableException.class, ServletRequestBindingException.class})
    @ResponseBody
    public BaseOutVO throwsHttpMessageNotReadableException() {
        return VOFactory.getBaseOutVO(DataCommonVOMessageEnum.COMMON_FAILED.getCode(),
                "缺少参数");
    }

    @ExceptionHandler(value = {ErrorCodeException.class})
    @ResponseBody
    public BaseOutVO throwsErrorCodeException(ErrorCodeException e) {
        log.error("业务异常:{}", e);
        return VOFactory.getBaseOutVO(e.getCode().code(),
                e.getMessage());
    }

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public BaseOutVO throwsException(Exception e) {
        log.error("系统异常:{}", e);
        return VOFactory.getBaseOutVO(DataCommonVOMessageEnum.COMMON_FAILED.getCode(),
                "系统异常");
    }
}
